<template>
  <a-modal
    class="fillinfo-modal"
    v-model:open="dialogVisible"
    :title="$t('form.apply.modal_title')"
    :footer="null"
    @cancel="closeDialog"
    width="37.5vw"
  >
    <div class="header">1. {{ $t("form.apply.title_1") }}</div>
    <!-- 表单 数据 -->
    <div class="form">
      <a-form labelAlign="left" ref="formRef" :model="formData">
        <div class="form-inline">
          <a-form-item
            :label="$t('form.apply.form.item_1.label')"
            name="last_name"
            :rules="[
              {
                required: true,
                message: $t('form.apply.form.item_1.rules.error_1'),
                trigger: 'blur',
              },
            ]"
          >
            <a-input
              size="large"
              allowClear
              :maxlength="30"
              v-model:value.trim="formData.last_name"
            ></a-input>
          </a-form-item>
          <a-form-item
            :label="$t('form.apply.form.item_2.label')"
            name="first_name"
            :rules="[
              {
                required: true,
                message: $t('form.apply.form.item_2.rules.error_1'),
                trigger: 'blur',
              },
            ]"
          >
            <a-input
              size="large"
              allowClear
              
              :maxlength="30"
              v-model:value.trim="formData.first_name"
            ></a-input>
          </a-form-item>
          <a-form-item
            :label="`${$t('form.apply.form.item_3.label')}`"
            name="dob"
            :rules="[
              {
                required: true,
                message: $t('form.apply.form.item_3.rules.error_1'),
                trigger: 'blur',
              },
            ]"
          >
            <a-date-picker
              size="large"
              v-model:value="formData.dob"
              value-format="YYYY-MM-DD"
              :placeholder="$t('form.apply.form.item_3.rules.error_1')"
              :allowClear="false"
            />
          </a-form-item>
          <a-form-item
            :label="$t('form.apply.form.item_4.label')"
            name="country"
            :rules="[
              {
                required: true,
                message: $t('form.apply.form.item_4.rules.error_1'),
                trigger: 'blur',
              },
            ]"
          >
            <a-select
              v-model:value="formData.country"
              show-search
              placeholder="Select a country"
              :options="countryStore.countrySelectOptions"
              :filter-option="filterOption"
              @search="saveCountrySelectValue"
            ></a-select>
          </a-form-item>
          <a-form-item
            :label="$t('form.apply.form.item_5.label')"
            name="telephone"
            :rules="[
              { required: true, validator: checkPhone, trigger: 'blur' },
            ]"
          >
            <a-input
              size="large"
              allowClear
              type="tel"
              v-model:value="formData.telephone"
            ></a-input>
          </a-form-item>
          <a-form-item
            :rules="[
              { required: true, validator: checkEmail, trigger: 'blur' },
            ]"
            :label="$t('form.apply.form.item_7.label')"
            name="email"
          >
            <a-input
              size="large"
              allowClear
              v-model:value="formData.email"
            ></a-input>
          </a-form-item>
        </div>
        <a-form-item
          :label="$t('form.apply.form.item_8.label')"
          name="fileList"
          :rules="[
            { required: true, validator: checkFileList, trigger: 'blur' },
          ]"
        >
          <a-upload
            list-type="picture-card"
            :maxCount="1"
            v-model:file-list="formData.fileList"
          >
            <div>
              <PlusOutlined />
              <div class="upload-text">{{ $t("btnText.upload_idcard") }}</div>
            </div>
          </a-upload>
        </a-form-item>
      </a-form>
    </div>
    <div class="header">2. 2. {{ $t("form.apply.title_2") }}</div>
    <!-- 复选框 数据 -->
    <div class="form checkbox-form">
      <template v-for="(item, index) in checkList" :key="item.title">
        <div class="table">
          <template v-if="item.has_son == 'yes'">
            <div class="table-header border-bottom cell">
              {{ item.title }}
            </div>
            <div class="table-content">
              <div
                class="table-row border-bottom"
                :class="[i % 2 == 0 ? 'background' : '']"
                v-for="(item2, i) in item.list2"
                :key="i"
              >
                <div class="cell">
                  <a-checkbox v-model:checked="item2.checked">{{
                    item2.title
                  }}</a-checkbox>
                </div>
              </div>
            </div>
          </template>
          <template v-else-if="item.has_son == 'no'">
            <div class="table-content">
              <div
                class="table-row border-bottom"
                :class="[index % 2 == 0 ? 'background' : '']"
              >
                <div class="cell">
                  <a-checkbox v-model:checked="item.checked">{{
                    item.title
                  }}</a-checkbox>
                </div>
              </div>
            </div>
          </template>
        </div>
      </template>
    </div>
    <div class="header">3. {{ $t("form.apply.title_3") }}</div>
    <div class="declare-checkbox">
      <a-checkbox-group
        v-model:value="declareValues"
        :options="declareOptions"
      />
    </div>
    <footer>
      <div class="left">
        <a-button type="default" size="large" @click="checkAll">{{
          isCheckAll ? $t("btnText.cancel_check_all") : $t("btnText.check_all")
        }}</a-button>
      </div>
      <div class="right">
        <a-button type="default" size="large" @click="closeDialog">{{
          $t("btnText.cancel")
        }}</a-button>
        <a-button
          type="primary"
          size="large"
          @click="submit"
          :loading="submitLoading"
          >{{ $t("btnText.imed_submit") }}</a-button
        >
      </div>
    </footer>
  </a-modal>
</template>

<script setup lang="ts">
import { message } from "ant-design-vue";
import { computed, getCurrentInstance, ref, watch } from "vue";
import type {
  CourseSubmitCreateParams,
  OutlineItem,
} from "../../types/aviation";
import { RegMobile, RegEmail } from "../../data/reg";
import {
  useMemberStore,
  useCountryStore,
  useGlobalStore,
  useCacheStore,
} from "../../store";
import { postUploadSingleImg } from "../../api/api";
import { postCourseApply, postCourseSubmitTab } from "../../api/aviation";
const memberStore = useMemberStore();
const countryStore = useCountryStore();
const globalStore = useGlobalStore();

const saveCountrySelectValue = (v) => {
  if (v) {
    formData.value.country = v;
  }
};

const props = defineProps<{
  checkList: OutlineItem[];
  course_id: number;
  title: string;
}>();

const declareOptions = computed(() => {
  return globalStore.aviationDetailApplyDeclare?.map((item: any) => {
    return {
      label: item.title,
      value: item.title,
    };
  });
});
const declareValues = ref([]);

const $t = getCurrentInstance()?.appContext.config.globalProperties.$t;

const filterOption = (input: string, option: any) => {
  return option.codes?.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};
const checkAll = () => {
  if (isCheckAll.value) {
    clearCheckAll();
    return;
  }
  props.checkList.map((item: OutlineItem) => {
    item.checked = true;
    item.list2!.map((item2: OutlineItem) => {
      item2.checked = true;
    });
  });
};

// 判断是否全选了
const isCheckAll = computed(() => {
  let flag = true;
  props.checkList.map((item: OutlineItem) => {
    if (!item.checked) flag = false;
  });
  return flag;
});

const clearCheckAll = () => {
  declareValues.value = [];

  props.checkList.map((item: OutlineItem) => {
    item.checked = false;
    item.list2!.map((item2: OutlineItem) => {
      item2.checked = false;
    });
  });
};
const checkPhone = async (_rule: any, value: string) => {
  if (!value) {
    return Promise.reject($t("form.apply.form.item_5.rules.error_1"));
  }
  let regPhone = RegMobile;
  if (!regPhone.test(value)) {
    return Promise.reject($t("reg_rules.mobile"));
  } else {
    return Promise.resolve();
  }
};

const checkEmail = async (_rule: any, value: string) => {
  if (!value) {
    return Promise.reject($t("form.apply.form.item_7.rules.error_1"));
  }
  let regEmail = RegEmail;
  if (!regEmail.test(value)) {
    return Promise.reject($t("reg_rules.email"));
  } else {
    return Promise.resolve();
  }
};
const checkBankID = async (_rule: any, value: string) => {
  if (!value) {
    return Promise.reject($t("form.apply.form.item_6.rules.error_1"));
  } else {
    return Promise.resolve();
  }
  let regEmail = RegEmail;
  if (!regEmail.test(value)) {
    return Promise.reject($t("reg_rules.bankId"));
  } else {
    return Promise.resolve();
  }
};

const checkFileList = async (_rule: any, value: string) => {
  if (value.length !== 1) {
    return Promise.reject($t("form.apply.form.item_8.rules.error_1"));
  } else {
    return Promise.resolve();
  }
};

// 表单数据
const formData = ref<CourseSubmitCreateParams & { fileList: any[] }>({
  last_name: memberStore.profile?.last_name || "",
  first_name: memberStore.profile?.first_name || "",
  country: countryStore.getCountryById(memberStore.profile?.country_id!) || "",
  dob: memberStore.profile?.birthday || "",
  telephone: memberStore.profile?.mobile || "",
  card_no: "",
  email: memberStore.profile?.email || "",
  identity_document: [],
  course_id: 0,
  course_ku_list_id: "",
  fileList: [],
});

const formRef = ref();
const submitLoading = ref(false);
const submit = () => {
  formRef.value.validate().then(async () => {
    if (
      declareValues.value.length !==
      globalStore?.aviationDetailApplyDeclare?.length
    ) {
      message.warning($t("message.agree_read"));
      return;
    }
    submitLoading.value = true;
    // 上传图片1
    let file1 = formData.value.fileList[0].originFileObj;
    let formDataValue = new FormData();
    formDataValue.append("file", file1);
    let { img: success_img1 } = await postUploadSingleImg(formDataValue);
    // 获取数据
    formData.value.course_id = props.course_id;
    formData.value.course_ku_list_id = getCheckListItem();
    // 上传成功的图片添加进表单
    formData.value.identity_document = [success_img1!];
    if (isNaN(parseInt(formData.value.country))) {
      formData.value.country = countryStore.getCountryIdByTitle(
        formData.value.country
      );
    }
    // 申请报名请求接口
    let res = await postCourseApply(formData.value);
    if (res.code === 200) {
      message.success($t("message.apply_success"));
    } else {
      submitLoading.value = false;
      message.warning($t("message.warning.have_applied"));
    }
    closeDialog();
  });
};

const getCheckListItem = () => {
  let arr: number[] = [];
  props.checkList.map((item: OutlineItem) => {
    if (item.has_son == "yes") {
      item.list2?.forEach((item2) => {
        if (item2.checked) {
          arr.push(item2.id);
        }
      });
    } else {
      if (item.checked) {
        arr.push(item.id);
      }
    }
  });
  return arr.join(",");
};

// 弹窗操作
const dialogVisible = ref(false);

const showDialog = () => {
  dialogVisible.value = true;
};

const closeDialog = () => {
  dialogVisible.value = false;
  submitLoading.value = false;
  clearCheckAll();
  formData.value = {
    last_name: memberStore.profile?.last_name || "",
    first_name: memberStore.profile?.first_name || "",
    country:
      countryStore.getCountryById(memberStore.profile?.country_id!) || "",
    dob: memberStore.profile?.birthday || "",
    telephone: memberStore.profile?.mobile || "",
    card_no: "",
    email: memberStore.profile?.email || "",
    identity_document: [],
    course_id: 0,
    course_ku_list_id: "",
    fileList: [],
  };
};

defineExpose({
  show: showDialog,
  close: closeDialog,
});
</script>
<style>
.fillinfo-modal {
  width: 720px !important;
}
</style>
<style scoped lang="less">
:deep(.ant-upload-list) {
  display: flex;
  & > [class^="ant-upload"] {
    width: 120px !important;
    height: 160px !important;
    display: flex !important;
    flex-direction: column;
    position: relative;
    align-items: center;
    font-size: 14px;
    color: #ccd6de;
    justify-content: center;
    border: 1px solid #ccd6de !important;
    border-radius: 10px;
    overflow: hidden;
    background-color: #fff !important;
    .ant-upload-list-item {
      padding: 0;
      border: 0;
      &::before {
        width: 100% !important;
        height: 100% !important;
      }
    }
    .anticon {
      font-size: 48px;
    }
    .upload-text {
      margin-top: 8px;
    }
  }
}

.form-inline {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  & > div {
    &:nth-child(2n) {
      margin-left: 48px;
      :deep(label) {
        width: 75px;
      }
    }
  }
}
:deep(.ant-upload-list-item-actions) {
  display: flex;
  justify-content: center;
  align-items: center;
  & > * {
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .anticon {
    display: inline-block;
    &.anticon-eye {
      display: none;
    }
  }
}
.ant-form {
  :deep(.ant-form-item) {
    margin-bottom: 24px !important;
    .ant-form-item-control-input {
      min-height: 32px !important;
    }
    .ant-form-item-control-input-content {
      display: flex !important;
    }
  }
  :deep(.ant-form-item label) {
    width: 130px;
  }
  :deep(.ant-form-item-label) {
    display: flex;
    padding-top: 3px;
  }
  .ant-picker {
    display: block;
  }
}

.declare-checkbox {
  padding: 10px;
  :deep(.ant-checkbox-group) {
    flex-direction: column;
    gap: 5px;
    .ant-checkbox + span {
      white-space: normal;
    }
  }
}

footer {
  display: flex;
  justify-content: space-between;
  margin-top: 48px;
  .right {
    display: flex;
    gap: 12px;
  }
}
.table {
  border: 1px solid #e6edf2;
  .table-header {
    text-align: left;
  }
  .table-content {
    .table-row:last-child {
      border-bottom-color: transparent;
    }
  }
  // &:first-child {
  //   margin-bottom: 24px;
  // }
}
.table-row {
  &.background {
    background-color: #f5f9fa;
  }
}
.header {
  padding: 12px 8px;
  background-color: #3d88f2;
  color: #fff;
  font-size: 18px;
  margin-top: 24px;
}
.form {
  margin: 24px 0;
  display: flex;
  flex-direction: column;
  gap: 12px;
}
</style>
